// 知识图谱管理系统 JavaScript

// API 基础 URL
const API_BASE = '/api';

// 全局变量
let graphChart = null;
let graphData = { nodes: [], links: [] };
let allItems = [];
let allRelations = [];

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
});

// 初始化应用
function initializeApp() {
    initializeGraph();
    loadData();
    setupEventListeners();
}

// 初始化图谱
function initializeGraph() {
    const chartContainer = document.getElementById('knowledgeGraph');
    graphChart = echarts.init(chartContainer);
    
    // 设置初始配置
    const option = {
        title: {
            text: '知识图谱',
            subtext: '拖拽节点可调整位置',
            left: 'center',
            top: 20,
            textStyle: {
                color: '#333',
                fontSize: 18,
                fontWeight: 'bold'
            },
            subtextStyle: {
                color: '#666',
                fontSize: 12
            }
        },
        tooltip: {
            trigger: 'item',
            formatter: function(params) {
                if (params.dataType === 'node') {
                    return `<div style="padding: 10px;">
                        <h4 style="margin: 0 0 8px 0; color: #333;">${params.data.name}</h4>
                        <p style="margin: 0; color: #666; font-size: 12px;">节点ID: ${params.data.id}</p>
                        <p style="margin: 4px 0 0 0; color: #666; font-size: 12px;">关系数: ${params.data.symbolSize / 5}</p>
                    </div>`;
                } else if (params.dataType === 'edge') {
                    return `<div style="padding: 10px;">
                        <h4 style="margin: 0 0 8px 0; color: #333;">${params.data.relationLabel}</h4>
                        <p style="margin: 0; color: #666; font-size: 12px;">${params.data.source} → ${params.data.target}</p>
                        ${params.data.description ? `<p style="margin: 4px 0 0 0; color: #666; font-size: 12px;">${params.data.description}</p>` : ''}
                    </div>`;
                }
                return '';
            },
            backgroundColor: 'rgba(255, 255, 255, 0.95)',
            borderColor: '#ddd',
            borderWidth: 1,
            textStyle: {
                color: '#333'
            }
        },
        animationDurationUpdate: 1500,
        animationEasingUpdate: 'quinticInOut',
        series: [{
            name: '知识图谱',
            type: 'graph',
            layout: 'force',
            data: [],
            links: [],
            categories: [
                { name: '实体', itemStyle: { color: '#667eea' } },
                { name: '高亮', itemStyle: { color: '#ff6b6b' } }
            ],
            roam: true,
            label: {
                show: true,
                position: 'right',
                formatter: '{b}',
                fontSize: 12,
                color: '#333'
            },
            labelLayout: {
                hideOverlap: true
            },
            scaleLimit: {
                min: 0.4,
                max: 2
            },
            lineStyle: {
                color: 'source',
                curveness: 0.3,
                width: 2
            },
            emphasis: {
                focus: 'adjacency',
                lineStyle: {
                    width: 4
                },
                itemStyle: {
                    borderColor: '#fff',
                    borderWidth: 3
                }
            },
            force: {
                repulsion: 100,
                gravity: 0.05,
                edgeLength: [50, 200],
                layoutAnimation: true
            },
            draggable: true
        }]
    };
    
    graphChart.setOption(option);
    
    // 监听节点点击事件
    graphChart.on('click', function(params) {
        if (params.dataType === 'node') {
            showNodeDetails(params.data);
            highlightNode(params.data.id);
        }
    });
    
    // 监听图表完成事件
    graphChart.on('finished', function() {
        hideGraphLoading();
    });
    
    // 响应式调整
    window.addEventListener('resize', function() {
        graphChart.resize();
    });
}

// 设置事件监听器
function setupEventListeners() {
    // 物品表单提交
    document.getElementById('itemForm').addEventListener('submit', function(e) {
        e.preventDefault();
        addItem();
    });
    
    // 关系表单提交
    document.getElementById('relationForm').addEventListener('submit', function(e) {
        e.preventDefault();
        addRelation();
    });
    
    // 搜索功能
    document.getElementById('searchBtn').addEventListener('click', performSearch);
    document.getElementById('searchInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            performSearch();
        }
    });
    document.getElementById('clearSearchBtn').addEventListener('click', clearSearch);
    
    // 数据列表模态框打开时刷新数据
    document.getElementById('dataListModal').addEventListener('show.bs.modal', function() {
        loadModalData();
    });
}

// 加载所有数据
async function loadData() {
    showGraphLoading();
    await Promise.all([
        loadItems(),
        loadRelations()
    ]);
    await loadGraphData();
    updateStats();
}

// 显示图表加载状态
function showGraphLoading() {
    const container = document.getElementById('knowledgeGraph');
    const existingLoading = container.querySelector('.graph-loading');
    if (!existingLoading) {
        const loadingDiv = document.createElement('div');
        loadingDiv.className = 'graph-loading';
        loadingDiv.innerHTML = `
            <div class="loading"></div>
            <div>正在加载知识图谱...</div>
        `;
        container.appendChild(loadingDiv);
    }
}

// 隐藏图表加载状态
function hideGraphLoading() {
    const container = document.getElementById('knowledgeGraph');
    const loadingDiv = container.querySelector('.graph-loading');
    if (loadingDiv) {
        loadingDiv.remove();
    }
}

// 加载图谱数据
async function loadGraphData() {
    try {
        const response = await fetch(`${API_BASE}/graph`);
        const data = await response.json();
        
        if (data.success) {
            graphData = {
                nodes: data.data.nodes || [],
                links: data.data.edges || []
            };
            updateGraph();
        } else {
            showMessage('graphMessage', `加载图谱数据失败: ${data.message}`, 'error');
        }
    } catch (error) {
        console.error('加载图谱数据失败:', error);
        showMessage('graphMessage', '加载图谱数据失败，请检查网络连接', 'error');
        showEmptyGraph();
    }
}

// 更新图谱显示
function updateGraph() {
    if (!graphChart) return;
    
    // 清除空状态显示
    const container = document.getElementById('knowledgeGraph');
    const emptyState = container.querySelector('.empty-state');
    if (emptyState) {
        emptyState.remove();
    }
    
    if (graphData.nodes.length === 0) {
        showEmptyGraph();
        return;
    }
    
    console.log('更新图谱数据:', graphData); // 调试日志
    
    // 处理节点数据，确保ID类型一致
    const nodes = graphData.nodes.map(node => {
        const nodeId = String(node.id); // 确保ID为字符串类型
        const connections = graphData.links.filter(link => 
            String(link.source) === nodeId || String(link.target) === nodeId
        ).length;
        
        return {
            id: nodeId,
            name: node.name,
            symbolSize: Math.max(20, Math.min(60, 20 + connections * 5)),
            category: 0,
            itemStyle: {
                color: getNodeColor(connections),
                borderColor: '#fff',
                borderWidth: 2
            },
            label: {
                show: true,
                fontSize: Math.max(10, Math.min(14, 10 + connections)),
                color: '#333'
            }
        };
    });
    
    // 处理边数据，确保ID类型一致
    const links = graphData.links.map(link => ({
        source: String(link.source), // 确保ID为字符串类型
        target: String(link.target), // 确保ID为字符串类型
        relationLabel: getRelationTypeName(link.type),
        description: link.description || '',
        lineStyle: {
            color: getRelationColor(link.type),
            width: 2,
            type: link.type === 'is_a' ? 'dashed' : 'solid'
        },
        label: {
            show: true,
            formatter: getRelationTypeName(link.type),
            fontSize: 10,
            color: '#666',
            position: 'middle'
        }
    }));
    
    console.log('处理后的节点:', nodes);
    console.log('处理后的边:', links);
    
    // 完全重新设置图表选项
    const option = {
        title: {
            text: '知识图谱',
            subtext: `${nodes.length} 个知识点, ${links.length} 个关系`,
            left: 'center',
            top: 20,
            textStyle: {
                color: '#333',
                fontSize: 18,
                fontWeight: 'bold'
            },
            subtextStyle: {
                color: '#666',
                fontSize: 12
            }
        },
        tooltip: {
            trigger: 'item',
            formatter: function(params) {
                if (params.dataType === 'node') {
                    const connections = links.filter(link => 
                        link.source === params.data.id || link.target === params.data.id
                    ).length;
                    return `<div style="padding: 10px;">
                        <h4 style="margin: 0 0 8px 0; color: #333;">${params.data.name}</h4>
                        <p style="margin: 0; color: #666; font-size: 12px;">节点ID: ${params.data.id}</p>
                        <p style="margin: 4px 0 0 0; color: #666; font-size: 12px;">关系数: ${connections}</p>
                    </div>`;
                } else if (params.dataType === 'edge') {
                    return `<div style="padding: 10px;">
                        <h4 style="margin: 0 0 8px 0; color: #333;">${params.data.relationLabel}</h4>
                        <p style="margin: 0; color: #666; font-size: 12px;">${getNodeName(params.data.source)} → ${getNodeName(params.data.target)}</p>
                        ${params.data.description ? `<p style="margin: 4px 0 0 0; color: #666; font-size: 12px;">${params.data.description}</p>` : ''}
                    </div>`;
                }
                return '';
            },
            backgroundColor: 'rgba(255, 255, 255, 0.95)',
            borderColor: '#ddd',
            borderWidth: 1,
            textStyle: {
                color: '#333'
            }
        },
        animationDurationUpdate: 1500,
        animationEasingUpdate: 'quinticInOut',
        series: [{
            name: '知识图谱',
            type: 'graph',
            layout: 'force',
            data: nodes,
            links: links,
            categories: [
                { name: '实体', itemStyle: { color: '#667eea' } },
                { name: '高亮', itemStyle: { color: '#ff6b6b' } }
            ],
            roam: true,
            label: {
                show: true,
                position: 'right',
                formatter: '{b}',
                fontSize: 12,
                color: '#333'
            },
            labelLayout: {
                hideOverlap: true
            },
            scaleLimit: {
                min: 0.4,
                max: 2
            },
            lineStyle: {
                color: 'source',
                curveness: 0.3,
                width: 2
            },
            emphasis: {
                focus: 'adjacency',
                lineStyle: {
                    width: 4
                },
                itemStyle: {
                    borderColor: '#fff',
                    borderWidth: 3
                }
            },
            force: {
                repulsion: 100,
                gravity: 0.05,
                edgeLength: [50, 200],
                layoutAnimation: true
            },
            draggable: true
        }]
    };
    
    // 设置完整的选项
    graphChart.setOption(option, true); // true表示不合并，完全替换
    
    hideGraphLoading();
}

// 获取节点名称的辅助函数
function getNodeName(nodeId) {
    const node = graphData.nodes.find(n => String(n.id) === String(nodeId));
    return node ? node.name : '未知';
}

// 显示空图谱
function showEmptyGraph() {
    if (!graphChart) return;
    
    graphChart.setOption({
        series: [{
            data: [],
            links: []
        }]
    });
    
    const container = document.getElementById('knowledgeGraph');
    const existingEmpty = container.querySelector('.empty-state');
    if (!existingEmpty) {
        const emptyDiv = document.createElement('div');
        emptyDiv.className = 'empty-state';
        emptyDiv.innerHTML = `
            <i class="bi bi-diagram-3"></i>
            <h4>暂无图谱数据</h4>
            <p>请先添加一些物品和关系来构建知识图谱</p>
        `;
        container.appendChild(emptyDiv);
    }
    
    hideGraphLoading();
}

// 获取节点颜色
function getNodeColor(connections) {
    if (connections === 0) return '#bbb';
    if (connections <= 2) return '#667eea';
    if (connections <= 4) return '#38ef7d';
    if (connections <= 6) return '#f093fb';
    return '#ff6b6b';
}

// 获取关系颜色
function getRelationColor(type) {
    const colorMap = {
        'related_to': '#667eea',
        'is_a': '#38ef7d',
        'part_of': '#f093fb',
        'contains': '#ff9f40',
        'depends_on': '#ff6b6b',
        'similar_to': '#4bc0c0'
    };
    return colorMap[type] || '#999';
}

// 执行搜索
function performSearch() {
    const searchTerm = document.getElementById('searchInput').value.trim().toLowerCase();
    if (!searchTerm) {
        showMessage('graphMessage', '请输入搜索内容', 'error');
        return;
    }
    
    const matchedNodes = graphData.nodes.filter(node => 
        node.name.toLowerCase().includes(searchTerm)
    );
    
    if (matchedNodes.length === 0) {
        showMessage('graphMessage', `未找到包含 "${searchTerm}" 的实体`, 'error');
        return;
    }
    
    // 高亮匹配的节点
    matchedNodes.forEach(node => {
        highlightNode(node.id, false);
    });
    
    showMessage('graphMessage', `找到 ${matchedNodes.length} 个匹配的实体`, 'success');
    
    // 聚焦到第一个匹配项
    if (matchedNodes.length > 0) {
        focusOnNode(matchedNodes[0].id);
    }
}

// 清除搜索
function clearSearch() {
    document.getElementById('searchInput').value = '';
    clearHighlight();
    showMessage('graphMessage', '已清除搜索结果', 'success');
}

// 高亮节点
function highlightNode(nodeId, clearOthers = true) {
    if (!graphChart) return;
    
    const option = graphChart.getOption();
    if (!option || !option.series || !option.series[0] || !option.series[0].data) {
        return;
    }
    
    const nodes = option.series[0].data;
    
    nodes.forEach(node => {
        if (clearOthers) {
            // 清除其他高亮
            node.category = 0;
            node.itemStyle = {
                ...node.itemStyle,
                color: getNodeColor(getNodeConnections(node.id)),
                shadowBlur: 0
            };
        }
        
        if (String(node.id) === String(nodeId)) {
            // 高亮当前节点
            node.category = 1;
            node.itemStyle = {
                ...node.itemStyle,
                color: '#ff6b6b',
                shadowBlur: 20,
                shadowColor: '#ff6b6b'
            };
        }
    });
    
    graphChart.setOption({
        series: [{
            data: nodes
        }]
    });
}

// 清除高亮
function clearHighlight() {
    if (!graphChart) return;
    
    const option = graphChart.getOption();
    if (!option || !option.series || !option.series[0] || !option.series[0].data) {
        return;
    }
    
    const nodes = option.series[0].data;
    
    nodes.forEach(node => {
        node.category = 0;
        const connections = getNodeConnections(node.id);
        node.itemStyle = {
            ...node.itemStyle,
            color: getNodeColor(connections),
            shadowBlur: 0
        };
    });
    
    graphChart.setOption({
        series: [{
            data: nodes
        }]
    });
}

// 聚焦到节点
function focusOnNode(nodeId) {
    // 这里可以实现图谱视角移动到特定节点的功能
    // ECharts 当前版本可能需要通过数据处理来实现
}

// 获取节点连接数
function getNodeConnections(nodeId) {
    return graphData.links.filter(link => 
        String(link.source) === String(nodeId) || String(link.target) === String(nodeId)
    ).length;
}

// 显示节点详情
function showNodeDetails(nodeData) {
    const connections = getNodeConnections(nodeData.id);
    const relatedConnections = graphData.links.filter(link => 
        String(link.source) === String(nodeData.id) || String(link.target) === String(nodeData.id)
    );
    
    let detailsHtml = `
        <div style="padding: 15px;">
            <h4 style="margin: 0 0 15px 0; color: #333;">${nodeData.name}</h4>
            <p><strong>节点ID:</strong> ${nodeData.id}</p>
            <p><strong>连接数:</strong> ${connections}</p>
            <div style="margin-top: 10px;">
                <button class="btn btn-sm btn-outline-danger" onclick="deleteItemFromGraph('${nodeData.id}', '${escapeHtml(nodeData.name)}')">
                    <i class="bi bi-trash"></i> 删除实体
                </button>
            </div>
    `;
    
    if (relatedConnections.length > 0) {
        detailsHtml += '<p><strong>相关关系:</strong></p><ul style="max-height: 150px; overflow-y: auto;">';
        relatedConnections.forEach(link => {
            const otherNodeId = String(link.source) === String(nodeData.id) ? link.target : link.source;
            const otherNode = graphData.nodes.find(n => String(n.id) === String(otherNodeId));
            const direction = String(link.source) === String(nodeData.id) ? '→' : '←';
            detailsHtml += `<li style="margin-bottom: 5px;">
                ${getRelationTypeName(link.type)} ${direction} ${otherNode ? otherNode.name : '未知'}
                <button class="btn btn-xs btn-outline-danger ms-2" onclick="deleteRelationFromGraph('${link.source}', '${link.target}', '${link.type}')" style="font-size: 10px; padding: 2px 6px;">
                    <i class="bi bi-x"></i>
                </button>
            </li>`;
        });
        detailsHtml += '</ul>';
    }
    
    detailsHtml += '</div>';
    
    // 更新信息面板
    document.getElementById('graphInfo').innerHTML = detailsHtml;
}

// 刷新图谱
async function refreshGraph() {
    showGraphLoading();
    await loadGraphData();
    showMessage('graphMessage', '图谱已刷新', 'success');
}

// 重置图谱布局
function resetGraphLayout() {
    if (!graphChart) return;
    
    // 重新设置力导向布局
    graphChart.setOption({
        series: [{
            force: {
                repulsion: 100,
                gravity: 0.05,
                edgeLength: [50, 200],
                layoutAnimation: true
            }
        }]
    });
    
    showMessage('graphMessage', '图谱布局已重置', 'success');
}

// 加载模态框数据
function loadModalData() {
    displayModalItems(allItems);
    displayModalRelations(allRelations);
}

// 显示模态框中的物品列表
function displayModalItems(items) {
    const tbody = document.getElementById('modalItemsList');
    tbody.innerHTML = '';
    
    if (items.length === 0) {
        tbody.innerHTML = '<tr><td colspan="3" class="text-center text-muted">暂无物品</td></tr>';
        return;
    }
    
    items.forEach(item => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${item.id}</td>
            <td>${escapeHtml(item.name)}</td>
            <td>
                <button class="btn btn-sm btn-outline-primary" onclick="highlightNode('${item.id}'); focusOnNode('${item.id}')" title="在图谱中高亮">
                    <i class="bi bi-search"></i>
                </button>
                <button class="btn btn-sm btn-outline-danger" onclick="deleteItemWithRefresh(${item.id}, '${escapeHtml(item.name)}')" title="删除实体">
                    <i class="bi bi-trash"></i>
                </button>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// 显示模态框中的关系列表
function displayModalRelations(relations) {
    const tbody = document.getElementById('modalRelationsList');
    tbody.innerHTML = '';
    
    if (relations.length === 0) {
        tbody.innerHTML = '<tr><td colspan="4" class="text-center text-muted">暂无关系</td></tr>';
        return;
    }
    
    relations.forEach(relation => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${escapeHtml(relation.source_item_name || '未知')}</td>
            <td><span class="badge" style="background: ${getRelationColor(relation.relation_type)}">${escapeHtml(getRelationTypeName(relation.relation_type))}</span></td>
            <td>${escapeHtml(relation.target_item_name || '未知')}</td>
            <td>
                <button class="btn btn-sm btn-outline-primary" onclick="highlightRelationNodes('${relation.source_item_id}', '${relation.target_item_id}')" title="在图谱中高亮关系">
                    <i class="bi bi-eye"></i>
                </button>
                <button class="btn btn-sm btn-outline-danger" onclick="deleteRelationWithRefresh(${relation.id})" title="删除关系">
                    <i class="bi bi-trash"></i>
                </button>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// 原有功能保持不变
function showMessage(elementId, message, type = 'success') {
    // 如果是图表消息，显示在图表信息区域
    if (elementId === 'graphMessage') {
        const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
        const messageHtml = `<div class="alert ${alertClass}" style="margin: 10px 0;">${message}</div>`;
        
        // 临时显示在图表信息区域
        const graphInfo = document.getElementById('graphInfo');
        const originalContent = graphInfo.innerHTML;
        graphInfo.innerHTML = messageHtml;
        
        setTimeout(() => {
            graphInfo.innerHTML = originalContent;
        }, 3000);
        return;
    }
    
    const element = document.getElementById(elementId);
    if (!element) return;
    
    const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    element.innerHTML = `<div class="alert ${alertClass}">${message}</div>`;
    
    setTimeout(() => {
        element.innerHTML = '';
    }, 3000);
}

async function loadItems() {
    try {
        const response = await fetch(`${API_BASE}/items`);
        const data = await response.json();
        
        if (data.success) {
            allItems = data.data;
            updateItemSelects(data.data);
        } else {
            showMessage('itemMessage', `加载物品失败: ${data.message}`, 'error');
        }
    } catch (error) {
        console.error('加载物品失败:', error);
        showMessage('itemMessage', '加载物品失败，请检查网络连接', 'error');
    }
}

function updateItemSelects(items) {
    const sourceSelect = document.getElementById('sourceItem');
    const targetSelect = document.getElementById('targetItem');
    
    sourceSelect.innerHTML = '<option value="">请选择源物品</option>';
    targetSelect.innerHTML = '<option value="">请选择目标物品</option>';
    
    items.forEach(item => {
        const option1 = new Option(item.name, item.id);
        const option2 = new Option(item.name, item.id);
        sourceSelect.appendChild(option1);
        targetSelect.appendChild(option2);
    });
}

async function addItem() {
    const nameInput = document.getElementById('itemName');
    const name = nameInput.value.trim();
    
    if (!name) {
        showMessage('itemMessage', '请输入物品名称', 'error');
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE}/items`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ name: name })
        });
        
        const data = await response.json();
        
        if (data.success) {
            showMessage('itemMessage', `物品 "${data.data.name}" 添加成功！`);
            nameInput.value = '';
            
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('addItemModal'));
            if (modal) modal.hide();
            
            // 刷新数据和图谱
            await loadData();
        } else {
            showMessage('itemMessage', `添加失败: ${data.message}`, 'error');
        }
    } catch (error) {
        console.error('添加物品失败:', error);
        showMessage('itemMessage', '添加失败，请检查网络连接', 'error');
    }
}

async function deleteItem(itemId, itemName) {
    if (!confirm(`确定要删除物品 "${itemName}" 吗？这将同时删除相关的所有关系。`)) {
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE}/items/${itemId}`, {
            method: 'DELETE'
        });
        
        const data = await response.json();
        
        if (data.success) {
            showMessage('graphMessage', `物品 "${itemName}" 删除成功！`);
            await loadData();
        } else {
            showMessage('graphMessage', `删除失败: ${data.message}`, 'error');
        }
    } catch (error) {
        console.error('删除物品失败:', error);
        showMessage('graphMessage', '删除失败，请检查网络连接', 'error');
    }
}

async function loadRelations() {
    try {
        const response = await fetch(`${API_BASE}/relations`);
        const data = await response.json();
        
        if (data.success) {
            allRelations = data.data;
        } else {
            showMessage('relationMessage', `加载关系失败: ${data.message}`, 'error');
        }
    } catch (error) {
        console.error('加载关系失败:', error);
        showMessage('relationMessage', '加载关系失败，请检查网络连接', 'error');
    }
}

function getRelationTypeName(type) {
    const typeMap = {
        'related_to': '相关',
        'is_a': '是一个',
        'part_of': '属于',
        'contains': '包含',
        'depends_on': '依赖于',
        'similar_to': '相似于'
    };
    return typeMap[type] || type;
}

async function addRelation() {
    const sourceItemId = document.getElementById('sourceItem').value;
    const targetItemId = document.getElementById('targetItem').value;
    const relationType = document.getElementById('relationType').value;
    const description = document.getElementById('description').value.trim();
    
    if (!sourceItemId || !targetItemId) {
        showMessage('relationMessage', '请选择源物品和目标物品', 'error');
        return;
    }
    
    if (sourceItemId === targetItemId) {
        showMessage('relationMessage', '源物品和目标物品不能相同', 'error');
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE}/relations`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                source_item_id: parseInt(sourceItemId),
                target_item_id: parseInt(targetItemId),
                relation_type: relationType,
                description: description
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            showMessage('relationMessage', '关系添加成功！');
            
            // 重置表单
            document.getElementById('sourceItem').value = '';
            document.getElementById('targetItem').value = '';
            document.getElementById('relationType').value = 'related_to';
            document.getElementById('description').value = '';
            
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('addRelationModal'));
            if (modal) modal.hide();
            
            // 刷新数据和图谱
            await loadData();
        } else {
            showMessage('relationMessage', `添加失败: ${data.message}`, 'error');
        }
    } catch (error) {
        console.error('添加关系失败:', error);
        showMessage('relationMessage', '添加失败，请检查网络连接', 'error');
    }
}

async function deleteRelation(relationId) {
    if (!confirm('确定要删除这个关系吗？')) {
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE}/relations/${relationId}`, {
            method: 'DELETE'
        });
        
        const data = await response.json();
        
        if (data.success) {
            showMessage('graphMessage', '关系删除成功！');
            await loadData();
        } else {
            showMessage('graphMessage', `删除失败: ${data.message}`, 'error');
        }
    } catch (error) {
        console.error('删除关系失败:', error);
        showMessage('graphMessage', '删除失败，请检查网络连接', 'error');
    }
}

function updateStats() {
    document.getElementById('itemCount').textContent = allItems.length;
    document.getElementById('relationCount').textContent = allRelations.length;
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// 从图谱中删除实体
async function deleteItemFromGraph(itemId, itemName) {
    if (!confirm(`确定要删除实体 "${itemName}" 吗？这将同时删除所有相关的关系。`)) {
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE}/items/${itemId}`, {
            method: 'DELETE'
        });
        
        const data = await response.json();
        
        if (data.success) {
            showMessage('graphMessage', `实体 "${itemName}" 删除成功！`);
            // 立即刷新数据和图谱
            await loadData();
            // 清空详情面板
            resetGraphInfo();
        } else {
            showMessage('graphMessage', `删除失败: ${data.message}`, 'error');
        }
    } catch (error) {
        console.error('删除实体失败:', error);
        showMessage('graphMessage', '删除失败，请检查网络连接', 'error');
    }
}

// 从图谱中删除关系
async function deleteRelationFromGraph(sourceId, targetId, relationType) {
    // 找到对应的关系ID
    const relation = allRelations.find(r => 
        String(r.source_item_id) === String(sourceId) && 
        String(r.target_item_id) === String(targetId) && 
        r.relation_type === relationType
    );
    
    if (!relation) {
        showMessage('graphMessage', '找不到要删除的关系', 'error');
        return;
    }
    
    const sourceName = getNodeName(sourceId);
    const targetName = getNodeName(targetId);
    
    if (!confirm(`确定要删除关系 "${sourceName} → ${targetName} (${getRelationTypeName(relationType)})" 吗？`)) {
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE}/relations/${relation.id}`, {
            method: 'DELETE'
        });
        
        const data = await response.json();
        
        if (data.success) {
            showMessage('graphMessage', '关系删除成功！');
            // 立即刷新数据和图谱
            await loadData();
            // 重新显示节点详情（如果还存在）
            const node = graphData.nodes.find(n => String(n.id) === String(sourceId));
            if (node) {
                showNodeDetails({id: sourceId, name: node.name});
            }
        } else {
            showMessage('graphMessage', `删除失败: ${data.message}`, 'error');
        }
    } catch (error) {
        console.error('删除关系失败:', error);
        showMessage('graphMessage', '删除失败，请检查网络连接', 'error');
    }
}

// 重置图谱信息面板
function resetGraphInfo() {
    document.getElementById('graphInfo').innerHTML = `
        <div class="info-item">
            <strong>操作提示：</strong>
            <ul>
                <li>拖拽节点调整位置</li>
                <li>点击节点查看详情</li>
                <li>使用搜索框查找实体</li>
                <li>滚轮缩放图谱</li>
            </ul>
        </div>
    `;
}

// 带刷新的删除实体函数（用于模态框）
async function deleteItemWithRefresh(itemId, itemName) {
    if (!confirm(`确定要删除实体 "${itemName}" 吗？这将同时删除所有相关的关系。`)) {
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE}/items/${itemId}`, {
            method: 'DELETE'
        });
        
        const data = await response.json();
        
        if (data.success) {
            showMessage('graphMessage', `实体 "${itemName}" 删除成功！`);
            // 刷新所有数据
            await loadData();
            // 刷新模态框数据
            loadModalData();
            // 重置图谱信息面板
            resetGraphInfo();
        } else {
            showMessage('graphMessage', `删除失败: ${data.message}`, 'error');
        }
    } catch (error) {
        console.error('删除实体失败:', error);
        showMessage('graphMessage', '删除失败，请检查网络连接', 'error');
    }
}

// 带刷新的删除关系函数（用于模态框）
async function deleteRelationWithRefresh(relationId) {
    if (!confirm('确定要删除这个关系吗？')) {
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE}/relations/${relationId}`, {
            method: 'DELETE'
        });
        
        const data = await response.json();
        
        if (data.success) {
            showMessage('graphMessage', '关系删除成功！');
            // 刷新所有数据
            await loadData();
            // 刷新模态框数据
            loadModalData();
        } else {
            showMessage('graphMessage', `删除失败: ${data.message}`, 'error');
        }
    } catch (error) {
        console.error('删除关系失败:', error);
        showMessage('graphMessage', '删除失败，请检查网络连接', 'error');
    }
}

// 高亮关系的两个节点
function highlightRelationNodes(sourceId, targetId) {
    // 清除所有高亮
    clearHighlight();
    
    // 高亮源节点
    setTimeout(() => {
        highlightNode(sourceId, false);
        // 稍后高亮目标节点
        setTimeout(() => {
            highlightNode(targetId, false);
        }, 300);
    }, 100);
}

// ============ 文本分析和智能构建功能 ============

// 提取三元组（预览功能）
async function extractTriplets() {
    const textInput = document.getElementById('analysisText');
    const text = textInput.value.trim();
    
    if (!text) {
        showAnalysisMessage('请输入要分析的文本', 'error');
        return;
    }
    
    // 获取关系标准化选项（暂时隐藏，默认关闭）
    const normalizeRelations = false; // document.getElementById('normalizeRelations').checked;
    
    try {
        showAnalysisLoading('正在分析文本，提取三元组...');
        
        const response = await fetch(`${API_BASE}/extract-triplets`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ 
                text: text,
                normalize_relations: normalizeRelations
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            displayTripletsPreview(data.triplets);
            const relationTypeText = data.normalized ? '标准化关系' : '原始关系';
            showAnalysisMessage(`成功提取到 ${data.count} 个三元组！（${relationTypeText}）`, 'success');
        } else {
            showAnalysisMessage(`提取失败: ${data.message}`, 'error');
        }
    } catch (error) {
        console.error('提取三元组失败:', error);
        showAnalysisMessage('提取失败，请检查网络连接', 'error');
    }
}

// 构建知识图谱
async function buildKnowledgeGraph() {
    const textInput = document.getElementById('analysisText');
    const text = textInput.value.trim();
    
    if (!text) {
        showAnalysisMessage('请输入要分析的文本', 'error');
        return;
    }
    
    // 获取关系标准化选项（暂时隐藏，默认关闭）
    const normalizeRelations = false; // document.getElementById('normalizeRelations').checked;
    const relationTypeText = normalizeRelations ? '标准化关系' : '原始关系';
    
    if (!confirm(`确定要从文本自动构建知识图谱吗？\n关系类型：${relationTypeText}\n这将会在数据库中添加新的实体和关系。`)) {
        return;
    }
    
    try {
        showAnalysisLoading('正在分析文本并构建知识图谱...');
        
        const response = await fetch(`${API_BASE}/build-kg-from-text`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ 
                text: text,
                normalize_relations: normalizeRelations
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            displayBuildResult(data);
            showAnalysisMessage(data.message, 'success');
            
            // 刷新图谱数据
            await loadData();
            
            // 5秒后自动关闭模态框
            setTimeout(() => {
                const modal = bootstrap.Modal.getInstance(document.getElementById('textAnalysisModal'));
                if (modal) modal.hide();
            }, 3000);
        } else {
            showAnalysisMessage(`构建失败: ${data.message}`, 'error');
        }
    } catch (error) {
        console.error('构建知识图谱失败:', error);
        showAnalysisMessage('构建失败，请检查网络连接', 'error');
    }
}

// 显示三元组预览
function displayTripletsPreview(triplets) {
    const previewDiv = document.getElementById('tripletsPreview');
    const contentDiv = document.getElementById('tripletsContent');
    
    if (triplets.length === 0) {
        contentDiv.innerHTML = '<p class="text-muted">未提取到有效的三元组</p>';
    } else {
        let html = '<table class="table table-sm table-bordered">';
        html += '<thead><tr><th>主体</th><th>关系</th><th>客体</th></tr></thead><tbody>';
        
        triplets.forEach((triplet, index) => {
            html += `<tr>
                <td><span class="badge bg-primary">${escapeHtml(triplet.subject)}</span></td>
                <td><span class="badge bg-success">${escapeHtml(triplet.relation)}</span></td>
                <td><span class="badge bg-info">${escapeHtml(triplet.object)}</span></td>
            </tr>`;
        });
        
        html += '</tbody></table>';
        contentDiv.innerHTML = html;
    }
    
    previewDiv.style.display = 'block';
}

// 显示构建结果
function displayBuildResult(data) {
    const resultDiv = document.getElementById('analysisResult');
    
    let html = '<div class="alert alert-success"><h6><i class="bi bi-check-circle"></i> 构建完成！</h6>';
    html += `<p><strong>统计信息：</strong></p>`;
    html += `<ul>
        <li>提取三元组: ${data.stats.triplets_extracted} 个</li>
        <li>新增实体: ${data.stats.items_added} 个</li>
        <li>新增关系: ${data.stats.relations_added} 个</li>
    </ul>`;
    
    if (data.stats.errors_count > 0) {
        html += `<p class="text-warning">处理过程中出现 ${data.stats.errors_count} 个错误</p>`;
        if (data.errors && data.errors.length > 0) {
            html += '<details><summary>查看错误详情</summary><ul class="small mt-2">';
            data.errors.forEach(error => {
                html += `<li class="text-danger">${escapeHtml(error)}</li>`;
            });
            html += '</ul></details>';
        }
    }
    
    html += '</div>';
    resultDiv.innerHTML = html;
}

// 显示分析消息
function showAnalysisMessage(message, type = 'success') {
    const resultDiv = document.getElementById('analysisResult');
    const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    resultDiv.innerHTML = `<div class="alert ${alertClass}">${message}</div>`;
    
    if (type === 'success') {
        setTimeout(() => {
            resultDiv.innerHTML = '';
        }, 5000);
    }
}

// 显示分析加载状态
function showAnalysisLoading(message) {
    const resultDiv = document.getElementById('analysisResult');
    resultDiv.innerHTML = `
        <div class="alert alert-info">
            <div class="d-flex align-items-center">
                <div class="loading me-3"></div>
                <div>${message}</div>
            </div>
        </div>
    `;
}

// 设置示例文本
function setExampleText(exampleId) {
    const textInput = document.getElementById('analysisText');
    
    const examples = {
        1: `大数据是指规模巨大、结构复杂的数据集合。它具有体量大、速度快、多样化的特征。数据科学是研究数据的学科。

HDFS是Hadoop分布式文件系统。它用于存储大规模数据集。MapReduce是分布式计算框架，负责处理大数据。

NoSQL数据库适合存储非结构化数据。MongoDB是文档型数据库。Redis是内存型数据库，常用于缓存。`,
        
        2: `Python是数据科学的主要编程语言。NumPy库用于数值计算。Pandas库负责数据处理和分析。

Matplotlib是数据可视化工具。Seaborn基于Matplotlib，提供更高级的统计图表。Jupyter Notebook是交互式开发环境。

Scikit-learn是机器学习库。它包含分类、回归、聚类等算法。TensorFlow和PyTorch是深度学习框架。`,
        
        3: `Apache Spark是大数据处理引擎。它支持批处理和流处理。Spark运行在Hadoop集群上。

Kafka是分布式消息队列系统。它用于实时数据传输。Elasticsearch是搜索引擎，支持全文检索。

Tableau是商业智能工具。它连接各种数据源，创建交互式仪表板。Power BI是微软开发的数据分析平台。`,
        
        4: `数据挖掘应用于电子商务推荐系统。亚马逊使用协同过滤算法推荐商品。Netflix运用机器学习预测用户偏好。

金融行业采用大数据进行风险控制。银行分析交易数据识别欺诈行为。保险公司利用数据科学评估风险。

医疗领域运用人工智能辅助诊断。IBM Watson应用于癌症治疗建议。谷歌DeepMind开发了蛋白质结构预测系统AlphaFold。`
    };
    
    if (examples[exampleId]) {
        textInput.value = examples[exampleId];
        // 清除之前的预览和结果
        document.getElementById('tripletsPreview').style.display = 'none';
        document.getElementById('analysisResult').innerHTML = '';
    }
}

// 清空文本分析结果
function clearAnalysisResults() {
    document.getElementById('analysisText').value = '';
    document.getElementById('tripletsPreview').style.display = 'none';
    document.getElementById('analysisResult').innerHTML = '';
}

// ============ 数据管理功能 ============

// 一键删除全部数据
async function clearAllData() {
    // 首先确认操作
    const confirmResult = confirm(
        '⚠️ 危险操作警告 ⚠️\n\n' +
        '您确定要删除所有数据吗？\n' +
        '此操作将会：\n' +
        '• 删除所有实体\n' +
        '• 删除所有关系\n' +
        '• 清空整个知识图谱\n\n' +
        '此操作不可撤销！'
    );
    
    if (!confirmResult) {
        return;
    }
    
    // 二次确认
    const secondConfirm = confirm(
        '再次确认：您真的要删除所有数据吗？\n\n' +
        '点击"确定"将立即执行删除操作！'
    );
    
    if (!secondConfirm) {
        return;
    }
    
    try {
        // 显示加载状态
        const loadingMessage = showMessage('正在删除所有数据...', 'info');
        
        const response = await fetch(`${API_BASE}/clear-all-data`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
            }
        });
        
        const data = await response.json();
        
        // 隐藏加载消息
        if (loadingMessage) {
            loadingMessage.remove();
        }
        
        if (data.success) {
            showMessage(
                `✅ ${data.message}`, 
                'success'
            );
            
            // 立即清空全局数据数组
            allItems = [];
            allRelations = [];
            graphData = { nodes: [], links: [] };
            
            // 立即更新统计显示
            updateStats();
            
            // 刷新图谱显示
            await loadData();
            
            // 清空搜索框
            document.getElementById('searchInput').value = '';
            
            console.log('数据删除统计:', data.stats);
        } else {
            showMessage(`❌ 删除失败: ${data.message}`, 'error');
        }
    } catch (error) {
        console.error('删除所有数据失败:', error);
        showMessage('❌ 删除失败，请检查网络连接', 'error');
    }
}


